package linkwechat.serviceimp;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import linkwechat.mapper.system.SysMenuMapper;
import linkwechat.pojo.SysMenu;
import linkwechat.sysservice.SysMenuService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class SysMenuServiceImp extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Resource
    SysMenuMapper sysMenuMapper;

//     查询所有菜单
    @Override
    public List<SysMenu> SelectMenuList() {
        List<SysMenu> linkMenus = selectList();
        return linkMenus;
    }

//    新增菜单
    @Override
    public int InsertMenu(SysMenu sysMenu) {
        return sysMenuMapper.InsertMenu(sysMenu);
    }

    //    修改菜单
    @Override
    public int UpdateMenu(SysMenu sysMenu) {
        return sysMenuMapper.UpdateMenu(sysMenu);
    }

    //    删除菜单
    @Override
    public int RemoveMenuById(Long menuId) {
        return sysMenuMapper.RemoveMenuById(menuId);
    }


    public List<SysMenu> selectList() {
//        查询所有部门
        List<SysMenu> listAll = sysMenuMapper.SelectMenuList();
        //根节点集合
        ArrayList<SysMenu> arrayList = new ArrayList<>();
        for (SysMenu linkMenu : listAll) {
            if (linkMenu.getParentId() == 0) {
                arrayList.add(linkMenu);
            }
        }
        for (SysMenu linkMenu : arrayList) {
            /* 获取根节点下的所有子节点 使用getChild方法*/
            List<SysMenu> childList = getChild(linkMenu.getMenuId().toString(), listAll);
            linkMenu.setChildren(childList);//给根节点设置子节点
        }
        return arrayList;
    }


    //    获取根节点
    public List<SysMenu> getChild(String id,List<SysMenu> allList){
        //子菜单
        List<SysMenu> childList = new ArrayList<>();
        for (SysMenu linkMenu : allList) {
            // 遍历所有节点，将所有菜单的父id与传过来的根节点的id比较
            //相等说明：为该根节点的子节点。
            if (linkMenu.getParentId().toString().equals(id)) {
                childList.add(linkMenu);
            }
        }
        //递归
        for (SysMenu linkMenu : childList) {
            linkMenu.setChildren(getChild(linkMenu.getMenuId().toString(), allList));
        }
        if (childList.size() == 0) {
            return new ArrayList<>();
        }
        return childList;
    }


}
